package cn.zniot.so.application.util;

import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;

public class PropertyUtil {
	
	private static PropertyUtil instance = new PropertyUtil();
	private PropertyUtil() {
	}
	public static synchronized PropertyUtil getInstance() {
		return instance;
	}
	
	/**
	 * key:ipAndPort
	 * value:盒子IMEI
	 */
	private  ConcurrentHashMap<String, String> mpIMEI = new ConcurrentHashMap<String, String>();
	
	/**
	 * key:ipAndPort
	 * value:0(盒子处于人车互动模式);1(盒子处于批处理上传指令模式)
	 */
//	private  ConcurrentHashMap<String, Integer> ZniotMode = new ConcurrentHashMap<String, Integer>();
	
	/**
	 * 通信IP端口与盒子IMEI映射
	 */
	public synchronized boolean addIpPortToIMEI(String ipAndPort,String imei) {
//		logger.debug("addIpPortToIMEI--"+ipAndPort + "," + imei);
		boolean result = true;
//<<<<<<< .mine
//		boolean containsKey = this.mpIMEI.containsKey(imei);
//		if (containsKey)
//		{
//			this.mpIMEI.replace(ipAndPort, imei);//不然不会替换掉
//		}
//=======
		if (this.mpIMEI.containsValue(imei)) {
			Iterator<String> iterator = mpIMEI.keySet().iterator();
			while(iterator.hasNext()) {
				String key =  iterator.next().toString();
				if (mpIMEI.get(key).equals(imei)) {
					this.mpIMEI.remove(key);
					break;
				}
			}
		}
//>>>>>>> .r134
		this.mpIMEI.put(ipAndPort, imei);
		return result;
	}
	
	public synchronized String getIMEIByIpPort(String ipAndPort) {
//		logger.debug("getIMEIByIpPort--"+ipAndPort);
		return this.mpIMEI.get(ipAndPort);
	}
	
	public synchronized boolean removeIpPortToIMEI(String ipAndPort) {
		boolean result = true;
		this.mpIMEI.remove(ipAndPort);
		return result;
	}	
	
	/**
	 * 方法名：getIpPortByIMEI(&String IMEI)
	 * 功　能：根据imei得到相对应的ip和port,服务器会同时有多个map，通过增强循环来获取相对应的值
	 * 参　数：String IMEI ——&车机的标识号
	 * 返回值：String - &车机的ip
	 */
	public synchronized String getIpPortByIMEI(String IMEI) {
		if (this.mpIMEI.size() > 0) {
			for (String IpAndPort : this.mpIMEI.keySet()) {
				if (this.mpIMEI.get(IpAndPort).equals(IMEI)) {
//					logger.debug("IMEI :" + IMEI + " , IpAndPort:" + IpAndPort);
					return (String) IpAndPort;
				}
			}
		}
		return null;
	}

}
